from MyTools.DBUtils import DBUtils
from Web_auto.db_options.loan_dao import LoanDAO
from Web_auto.db_options.user_dao import UserDAO


class BankCardDAO:
    def __init__(self):
        self.db = DBUtils(password='root', database='finance')

    def clean_bank(self):
        sql = "DELETE FROM `bankcard`"
        self.db.update(sql)

    def is_exist_bank(self, user, card_id):
        if user:
            uid = user[0][0]
            sql = '''
            SELECT * FROM bankcard WHERE `userid` = %s AND `cardNum` = %s
            '''
            return self.db.select(sql, (uid, card_id))
        else:
            print("查询银行卡失败！")

    def create_bankcard(self, user, bank_name, card_type, card_id, balance=None, defaultl=1):
        try:
            uid = user[0][0]
            sql = "INSERT INTO `bankcard`(`cardBank`,`type`,`cardNum`,`userId`,`balance`,`defaultl`) VALUES (%s,%s,%s,%s,%s,%s)"
            self.db.update(sql, (bank_name, card_type, card_id, uid, balance if balance is not None else 10000,
                                 defaultl if defaultl != 1 else 1))
        except Exception as e:
            print("添加银行卡失败！", e)

    def delete_bankcard(self, username, card_id):
        sql = '''
        DELETE FROM `bankcard` WHERE `cardNum` = %s AND `userid` = (
            SELECT `id` FROM `user` WHERE `username`=%s)
        '''
        self.db.select(sql, (username, card_id))

    def get_default_bankcard(self, username, default=1):
        user = UserDAO().get_user(username)
        userid = user[0][0]
        sql = "SELECT * FROM `bankcard` WHERE `userid` = %s AND `defaultl` = %s"
        return self.db.select(sql, (userid, default))


if __name__ == '__main__':
    udao = UserDAO()
    udao.clean_user()
    bcdao = BankCardDAO()
    ldao = LoanDAO()
    ldao.clean_loan()
    udao.create_user('lisi4', '123456', '666666', '张三4')
    lisi4 = udao.get_user('lisi4')
    # 创建银行卡
    bcdao.create_bankcard(lisi4, "伊拉克国民银行", 1, "1234567891548792", 0)
